package demo02;

import org.junit.Test;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/*
* 练习使用Executors获取ExecutorsService,然后关闭线程池
* */
public class MyTest04 {
     @Test
     public void test01(){
         //1.使用工厂类获取线程池对象
         ExecutorService es= Executors.newSingleThreadExecutor();
         //2.提交任务
         for(int i=1;i<=10;i++){
             es.submit(new MyRunable(i));
         }
         //关闭任务,shutdown方法,拒绝执行新任务，但会执行已提交的任务
         es.shutdown();
        // es.submit(new MyRunable(88));
     }

    @Test
    public void test02(){

        //1.使用工厂类获取线程池对象
        ExecutorService es= Executors.newSingleThreadExecutor(new ThreadFactory() {
            int n=1;
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"自定义的线程名称"+n++);
            }
        });
        //2.提交任务
        for(int i=1;i<=10;i++){
            es.submit(new MyRunable(i));
        }
        //3.shutdownNow.方法，会立即停止所有任务，并且会返回已经提交的任务
        List<Runnable> list=es.shutdownNow();
        for (Runnable runnable:list){
            System.out.println(runnable);
        }

    }


}

/*
* 任务类,包含一个任务编号，在任务中打印出一个线程正在执行的任务编号
*
* */
class MyRunable04 implements Runnable{

    private int id;

    public MyRunable04(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        //获取线程的名称,打印一句话
        String name=Thread.currentThread().getName();
        System.out.println(name+"执行了任务......."+this.id);
        /*try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    @Override
    public String toString() {
        return "MyRunable04{" +
                "id=" + id +
                '}';
    }
}
